package com.cddx.logistics.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OllamaService {
    @Value("${ollama.model}")
    private String model ;
    @Value("${ollama.url}")
    private  String url ;
    @Value("${ollama.stream}")
    private Boolean stream ;

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private JdbcTemplate jdbcTemplate;
    /**
     * 流式传输
     * @param prompt
     * @return
     */
    public Flux<String> streamQuery(String prompt) {
        Map<String , Object> map = new HashMap<>();
        map.put("model",model);
        map.put("prompt", prompt);
        map.put("stream", stream);
        return WebClient.create()
                .post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(map)
                .retrieve()
                .bodyToFlux(String.class)
                .map(this::extractResponseChunk)
                .filter(text -> !text.isEmpty());
    }

    private String extractResponseChunk(String json) {
        try {
            JsonNode node = new ObjectMapper().readTree(json);
            return node.path("response").asText();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 把响应内容整体返回 不采用流式传输
     * @param prompt
     * @return
     */
    public String queryModel(String prompt) {
        // Ollama API 请求体
        Map<String, Object> request = new HashMap<>();
        request.put("model", model);
        request.put("prompt", prompt);
        request.put("stream", false);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 发送请求
        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                new HttpEntity<>(request, headers),
                Map.class
        );
        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            return (String) response.getBody().get("response");
        }
        throw new RuntimeException("Ollama API 调用失败: " + response.getStatusCode());
    }



    public String handleDatabaseQuery(String prompt) {
        // Step 1: 解析用户问题并生成 SQL
        String sql = generateSQLFromPrompt(prompt);

        // Step 2: 执行 SQL 查询
        try {
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);

            // Step 3: 格式化结果
            return formatResult(result);
        } catch (Exception e) {
            return "数据库查询出错：" + e.getMessage();
        }
    }

    private String generateSQLFromPrompt(String prompt) {
        // 这里可以加入 NLP 或规则逻辑来生成 SQL
        if (prompt.contains("普通计划")) {
            String sql="select * from plan_normal";
            if(prompt.contains("今天"))
            {
                sql+=" where date=CURRENT_DATE";
            }
            return sql;
        }

        // 默认 fallback
        return null;
    }

    private String formatResult(List<Map<String, Object>> result) {
        // 简单 JSON 格式输出
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            return "无法格式化查询结果";
        }
    }

}

